<template>
	<div class="notice">
		<div class="notice_type clear">
			<div class="notice_type_check fl" v-if="!user_multistage" v-show="noticeList.length > 0">
				<div class="notice_type_check_1">
					<el-tooltip class="item" effect="dark" content="编辑" placement="top-start" v-if="notice_e">
						<i class="new_icn bianji" @click="changeShow"></i>
					</el-tooltip>
					<div class="box" :class="{'notice_m': isActive}">
						<el-tooltip class="item" effect="dark" content="全选" placement="top-start">
							<span>
								<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
							</span>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="删除" placement="top-start">
							<span class="new_icn dele_1" @click="removeList()"></span>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="已读" placement="top-start">
							<span class="new_icn Shape" @click="readList()"></span>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="返回" placement="top-start">
							<span class="new_icn left_1" @click="changeHide"></span>
						</el-tooltip>
					</div>
					<el-tooltip class="item" effect="dark" content="设置" placement="top-start">
						<i class="new_icn Shape3" @click="setNewsMessagee()"></i>
					</el-tooltip>
				</div>
			</div>
			<div class="notice_type_op fr">
				<label>
					<input type="radio" checked name="type">
					<span @click="bindNoticeStatus(3)">全部</span>
				</label>
				<label>
					<input type="radio" name="type">
					<span @click="bindNoticeStatus(0)">未读</span>
				</label>
				<label>
					<input type="radio" name="type">
					<span @click="bindNoticeStatus(1)">已读</span>
				</label>
				<div class="type_val box">
					<template>
						<el-select filterable v-model="mod_v" @change="changeModule()" placeholder="请选择">
							<template v-for="item in module">
								<el-option :key="item.name" :label="item.title" :value="item.name">
								</el-option>
							</template>
						</el-select>
					</template>
				</div>
			</div>
		</div>
		<ul class="mesg_list" v-loading="loading">
			<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
				<template v-for="(item, inx) in noticeList">
					<li class="noticeLs clear" :key="inx">
						<span class="box fl" v-if="isCheckbox">
							<el-checkbox :label="item"></el-checkbox>
						</span>
						<div class="noticeLs_r" :class="{'isWidth': isWidth}">
							<div class="noticeLs_1 clear">
								<el-badge v-if="!parseInt(item.is_read)" is-dot class="item"></el-badge>
								<i v-if="parseInt(item.is_top ) > 0">顶</i>
								<span>【 {{item.content_type}} 】</span>
								<div class="noticeLs_1_operation fr">
									<!-- <button type="text">标记已读</button> -->
									<button type="text" v-if="parseInt(item.is_top)" @click.stop="putToTop(item.id,0)">取消置顶</button>
									<button type="text" v-else @click.stop="putToTop(item.id,1)">置顶</button>
									<button type="text" @click.stop="markedRead(item)" v-if="!parseInt(item.is_read)">标记已读</button>
									<button type="text" @click="checkLook(inx,item)">查看</button>
								</div>
							</div>
							<div class="noticeLs_2">
								<span>{{item.name}}</span>
								<span>{{item.create_time.substring(5,16)}}</span>
							</div>
							<div class="noticeLs_3" v-html="item.title"></div>
						</div>
					</li>
				</template>
			</el-checkbox-group>
		</ul>
		<el-dialog title="消息自动删除设置" :visible.sync="newsVisible" width="400px" custom-class="del_new" :close-on-click-modal="false">
			<el-radio-group v-model="del_days">
				<el-radio :label="0">不自动删除</el-radio>
				<el-radio :label="30">自动删除30天前的已读消息（置顶除外）</el-radio>
				<el-radio :label="15">自动删除15天前的已读消息（置顶除外）</el-radio>
				<el-radio :label="7">自动删除7天前的已读消息（置顶除外）</el-radio>
			</el-radio-group>
			<div class="buttonCSS">
				<el-button type="primary" @click="messageSet">确定</el-button>
			</div>
		</el-dialog>
		<el-pagination v-if="total_number > 5" @current-change="changePage" :current-page="listNoticeParam.page_index" :page-size="listNoticeParam.page_size" layout="prev, pager, next" :total="total_number">
		</el-pagination>
		<div class="dependent" v-if="placeholder">
			<i class="ipm image_nofound"></i>
			<p>
				还没发现任何相关的内容哦~
			</p>
		</div>
		<el-dialog title="消息自动删除设置" :visible.sync="examineVisible" width="1000px" custom-class="del_new" :close-on-click-modal="false">
			<div class="">
				<!-- <examine-model :examineType='3'></examine-model> -->
			</div>
		</el-dialog>
		<!-- <examine-model ref="examine" :examineType='1'></examine-model> -->
	</div>
</template>
<script>
// 学生
let moduleS = [
	{ name: 'all___', title: '全部' },
	{ name: 'leave', title: '请假' },
	{ name: 'task', title: '任务' },
	{ name: 'live', title: '直播' },
	{ name: 'question', title: '提问' },
	{ name: 'class', title: '班级消息' },
	{ name: 'eva', title: '网络教研' },
	{ name: 'schedule_teamwork', title: '日程协同' },
]
// 家长
let moduleP = [
	{ name: 'all___', title: '全部' },
	{ name: 'leave', title: '请假' },
	{ name: 'task', title: '任务' },
	{ name: 'live', title: '直播' },
	{ name: 'question', title: '提问' },
	{ name: 'class', title: '班级消息' },
	{ name: 'eva', title: '网络教研' },
	{ name: 'schedule_teamwork', title: '日程协同' }
]
// 教师
let moduleT = [
	{ name: 'all___', title: '全部' },
	{ name: 'leave', title: '请假' },
	{ name: 'task', title: '任务' },
	{ name: 'live', title: '直播' },
	{ name: 'question', title: '提问' },
	{ name: 'class', title: '班级消息' },
	{ name: 'prepare', title: '协同备课' },
	{ name: 'master', title: '名师中心' },
	{ name: 'eva', title: '网络教研' },
	{ name: 'schedule_teamwork', title: '日程协同' }
]

// 管理员
let moduleA = [

	{ name: 'all___', title: '全部' },
	{ name: 'leave', title: '请假' },
	{ name: 'task', title: '任务' },
	{ name: 'live', title: '直播' },
	{ name: 'question', title: '提问' },
	{ name: 'prepare', title: '协同备课' },
	{ name: 'eva', title: '网络教研' }
]

import examineModel from './examine-model.vue'
export default {
	components: { examineModel },
	// name: '',
	data() {
		return {
			examineVisible: false,
			module: [
				// {name:'schedule',title:'排课评课'},
				// {name:'train',title:'教师培训'},
				// {name:'all___',title:'全部'},
				// {name:'leave',title:'请假'},
				// {name:'task',title:'任务'},
				// {name:'live',title:'直播'},
				// {name:'question',title:'提问'},
				// {name:'class',title:'班级消息'},
				// {name:'prepare',title:'协同备课'},
				// {name:'master',title:'名师中心'},
				// {name: 'alumni',title: '校友服务'},
				// {name:'schedule_teamwork',title:'日程协同'},
				// {name:'examine',title:'办公审批'},
				// {name:'competition',title:'活动赛事'},
				// {name:'email',title:'电子邮箱'},
				// {name:'car',title:'车辆管理'},
			],
			mod_v: 'all___',
			listNoticeParam: {
				module: [],
				user_id: this.$g.user_id,
				top_order: 'desc',
				data_type: 1,
				type: 1,
				page_size: 5,
				page_index: 1,
			},
			total_number: 0,
			noticeList: [],
			/*数据列表*/
			loading: true,
			placeholder: false,

			checkAll: false,
			/*全选*/
			checkedCities: [],
			/*选中的*/
			isIndeterminate: false,

			notice_e: true,
			isActive: false,
			isCheckbox: false,
			isWidth: false,
			newsVisible: false,
			del_days: 0,
			user_multistage: this.$store.state.userInfo.is_level,
			paramrURL: ''
		}
	},
	created() {
		this.setModule()
		this.getNoticeList();

	},
	watch: {
		"checkedCities": {
			handler(newVal, oldVal) {
				this.checkAll = newVal.length == this.noticeLength
			}
		}
	},
	computed:{
		noticeLength() {
			return this.noticeList.length
		}
	},
	methods: {
		/**
		 * 角色权限
		 * @DateTime 2020-05-14T09:09:05+0800
		 * @qiu_m
		 */
		setModule() {
			let checkModule = this.$store.getters.userInfo.check_rolebaseid;
			if (checkModule <= 3) {
				this.module = moduleA
			} else if (checkModule === 6 || checkModule === 8) {
				this.module = moduleT
			} else if (checkModule === 5) {
				this.module = moduleP
			} else if (checkModule === 4) {
				this.module = moduleS
			}
			if (this.$store.state.isSchool) {
				this.module.forEach((item, index) => {
					if (item.name == 'leave' || item.name == 'class') {
						this.module.splice(index, 1)
					}
				})
			}
		},
		/*
		标记已读
		 */
		markedRead(obj) {
			// this.isIndeterminate = true
			this.checkedCities = []

			let success = (res => {
				this.$store.commit('SET_NEWBADGE', new Date())
				this.$message.success(res.msg)
				this.getNoticeList();
			})
			this.$ajax({
				url: 'api/message/set_read',
				method: 'post',
				data: { type: 1, id: [obj.id] },
				func: { success: success }
			})
		},
		/**
		 * 修改消息自动删除设置
		 */
		setNewsMessagee() {
			this.newsVisible = true;

			let success = (res => {
				this.del_days = parseInt(res.data.del_days)
			});
			this.$ajax({
				url: 'api/message/message_set',
				method: 'get',
				params: {},
				func: { success: success }
			})
		},
		//置消息自动删除
		messageSet() {

			this.$confirm('是否设置消息自动删除?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them'
			}).then(() => {

				let success = (res => {
					this.newsVisible = false
					this.$message.success(res.msg)
					this.getNoticeList();
					this.$store.commit('SET_NEWBADGE', new Date())
				})
				this.$ajax({
					url: 'api/message/message_set',
					method: 'post',
					data: { del_days: this.del_days },
					func: { success: success }
				})
			}).catch(() => { this.newsVisible = false });
		},
		//勾选消息 --是否标为已读
		readList() {
			if (this.checkedCities.length == 0) {
				return this.$message.error('请勾选消息');

			};
			let idArr = [];
			for (var i = 0; i < this.checkedCities.length; i++) {
				if (this.checkedCities[i].id) {
					idArr.push(this.checkedCities[i].id)
				}
			}
			this.$confirm('是否标为已读?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them'
			}).then(() => {

				let success = (res => {
					this.$message.success(res.msg)
					this.checkAll = false;
					this.checkedCities = [];
					this.getNoticeList();
					this.$store.commit('SET_NEWBADGE', new Date())
				})
				this.$ajax({
					url: 'api/message/set_read',
					method: 'post',
					data: {
						type: 1,
						id: idArr
					},
					func: { success: success }
				})
			}).catch(() => {});
		},
		//勾选消息 -- 删除选择的消息
		removeList() {
			if (this.checkedCities.length == 0) {
				this.$message.error('请勾选消息');
				return
			};
			let idArr = [];
			for (var i = 0; i < this.checkedCities.length; i++) {
				if (this.checkedCities[i].id) {
					idArr.push(this.checkedCities[i].id)
				}
			}

			this.$confirm('是否删除选择的消息?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them'
			}).then(() => {

				let success = (res => {
					this.checkAll = false;
					this.checkedCities = [];
					this.$message.success(res.msg)
					this.listNoticeParam.page_index = 1;
					this.getNoticeList();
					this.$store.commit('SET_NEWBADGE', new Date())

				})
				this.$ajax({
					url: 'api/message/set_delete',
					method: 'delete',
					params: {
						type: 1,
						id: idArr
					},
					func: { success: success }
				})
			}).catch(() => {});
		},
		changeShow() {
			this.isActive = true
			this.notice_e = false
			this.isCheckbox = true
			this.isWidth = true
		},
		changeHide() {
			this.isActive = false
			this.notice_e = true
			this.isCheckbox = false
			this.isWidth = false
		},
		//全选--
		handleCheckAllChange(val) {
			this.checkedCities = val ? this.noticeList : [];
			this.isIndeterminate = false;
		},
		handleCheckedCitiesChange(value) {

			let checkedCount = value.length;
			this.checkAll = checkedCount === this.noticeList.length;
			this.isIndeterminate = checkedCount > 0 && checkedCount < this.noticeList.length;
		},
		//分页改变
		changePage(val) {
			this.listNoticeParam.page_index = val;
			this.checkAll = false;
			this.getNoticeList();
		},
		/*
    			筛选数据类型	        	
 	          */
		changeModule() {
			this.listNoticeParam.page_index = 1;
			this.getNoticeList();
		},
		//数据列表
		getNoticeList() {
			let success = (data => {
				this.noticeList = data.data.data;

				this.total_number = data.data.data_sum;
				this.loading = false;

				this.noticeList.length === 0 ? this.placeholder = true : this.placeholder = false
			})
			this.listNoticeParam.module = [];
			if (this.mod_v == "all___") {
				for (var i = this.module.length - 1; i >= 1; i--) {
					this.listNoticeParam.module.push(this.module[i].name);
				}
			} else {
				this.listNoticeParam.module.push(this.mod_v);

			}
			//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
			this.$ajax.get('api/message/message_user', { params: this.listNoticeParam, func: { success: success } })
		},

		//置顶 & 取消置顶
		putToTop(id, status) {

			this.checkedCities = []

			let success = (data => {
				this.$message.success(data.msg)
				this.getNoticeList();
			})
			this.$ajax.post('api/message/put_to_top', {
				id: id,
				status: status,
				user_id: this.$g.user_id
			}, { func: { success: success } })
		},

		//通知筛选
		bindNoticeStatus(status) {
			if (status === 3) {
				this.listNoticeParam.is_read = null;
			} else {
				this.listNoticeParam.is_read = status;
			}
			this.listNoticeParam.page_index = 1;
			this.getNoticeList();
		},
		resetNoticeParam() {
			this.listNoticeParam.total_number = 0;
			this.listNoticeParam.page_size = 5;
			this.listNoticeParam.page_index = 1;
		},
		//查看
		checkLook(inx, item) {
			this.$store.commit('SET_NEWBADGE', new Date())
			let BASE_URL = sessionStorage.getItem('host_addr')
			let host = sessionStorage.getItem('host')
			let redirectParams = sessionStorage.getItem('redirect_params')
			let classId = sessionStorage.getItem('classId')
			let link = ''


			if (this.noticeList[inx].is_read === 0) {
				let success = (data => {
					this.noticeList[inx].is_read = 1;
					this.getNoticeList()
				})
				this.$ajax.post('api/message/set_read', { id: item.id, type: 1 }, { func: { success: success } })
			}

			let module = this.noticeList[inx].module;
			let content_id = this.noticeList[inx].content_id
			let CheckSchoolAppCode =  sessionStorage.getItem( 'CheckSchoolAppCode' )
			let AppCode = null
			if (CheckSchoolAppCode != '') {
				AppCode = `&CheckSchoolAppCode=${CheckSchoolAppCode}`
			}
			switch (module) {

				case 'class': //班级消息
					if (this.$store.getters.userInfo.check_rolebaseid <= 3) {
						return this.$message.warning('管理员请到后台查看详情')
					}
					let cn = ''
					if (item.attach !== '') {
						cn = `
           						<p>${item.title}</p>
	           					<p>${this.noticeList[inx].content}</p>
	           					<div class="attach-url">
	           					<a href='${this.BASE_URL}/index/resource/download_video_file?name=${this.noticeList[inx].attach_name}&path=${this.noticeList[inx].attach}'>${this.noticeList[inx].attach_name}</a>
	           					</div>
	           					`;
					} else {
						cn = `
           						<p>${item.title}</p>
	           					<p>${this.noticeList[inx].content}</p>
	           					`;
					}

					this.$alert(cn, item.title, { dangerouslyUseHTMLString: true });
					break;
				case 'leave': //请假
					if (this.$store.getters.userInfo.check_rolebaseid <= 3) {
						return this.$message.warning('管理员请到后台查看详情')
					}
					this.$router.push('/class/leave/detail?id=' + content_id);
					break;
				case 'task': //任务
					if (this.$store.getters.userInfo.check_rolebaseid <= 3) {
						return this.$message.warning('管理员请到后台查看详情')
					}
					if (this.$store.state.userInfo.rolebaseid.includes(4)) {
						this.$router.push(`/class/homework/index?id=${classId}`)
					} else if (this.$store.state.userInfo.rolebaseid.includes(6)) {
						this.$router.push(`/class/task/detail?id=${classId}&tid=${content_id}`)
					}

					break;
				case 'live': //直播
					if (in_array(6, this.$store.getters.userInfo.role)) {
						this.$router.push('/teach/live/detailappoint?id=' + content_id);
					} else {

						let success = (res => {
							link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/home/liveRoom&id=${content_id}`
							window.open(link)
						});
						let fail = (res => {
							this.$message.error('直播已结束')
						})

						this.$ajax({
							method: 'get',
							url: 'api/live/check_is_liveend',
							params: { liveid: content_id },
							func: { success: success, fail: fail }
						})

					}
					break;
				case 'question': //提问
					if (this.noticeList[inx].template === 'question_1') {
						this.$router.push('/teach/ask/index');
					} else if (this.noticeList[inx].template === 'question_2') {

						this.$router.push('/learn/ask/index');
					}
					break;
				case 'prepare': //备课
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/prepare/see&id=${content_id}${AppCode}`
					window.open(link)
					break;
				case 'master': //名师中心
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/teach/space&id=${this.$g.user_id}${AppCode}`
					window.open(link)
					break;
				case 'schedule': //排课评课
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=course${AppCode}`
					window.open(link)
					break;
				case 'train': //教师培训
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=train${AppCode}`
					window.open(link)
					break;
				case 'schedule_teamwork':
					/*日程协同*/
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/calendar${AppCode}`
					window.open(link)
					break;
				case 'alumni':
					/*校友服务*/
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=`
					if (item.template == 'alumni_1') { /*拒绝*/

						return this.$message.warning(item.title)
					}
					// 通过
					else if (item.template == 'alumni_0') {
						link += `/alumni/album&id=${content_id}${AppCode}`;
					}
					// 删除
					else if (item.template == 'alumni_2') {
						link += `/alumni/mine${AppCode}`;
					}

					window.open(link)
					break;
				case 'examine':
					/*办公审批*/
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/examine`

					if (item.template == 'examine_3' || item.template == 'examine_4') {
						link += `&scanType=1${AppCode}`;
					}
					// 已通过、已拒绝、查看我发起的
					else if (item.template == 'examine_0' || item.template == 'examine_2' || item.template == 'examine_6') {
						link += `&scanType=3${AppCode}`;
					}
					// 抄送给我的
					else if (item.template == 'examine_1' || item.template == 'examine_5') {
						link += `&scanType=4${AppCode}`;
					} else {
						link += `&scanType=2${AppCode}`;
					}

					window.open(link)
					break;
				case 'competition':
					/*活动赛事*/
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/competition${AppCode}`
					window.open(link)
					break;
				case 'email':
					/*电子邮箱*/
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/email/inbox${AppCode}`
					window.open(link)
					break;
				case 'car':
					/*电子邮箱*/
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/vehicle/detail&id=${content_id}${AppCode}`
					window.open(link)
					break;
				case 'eva':
					/*网络教研*/
					link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/netteach/details&id=${content_id}${AppCode}`
					window.open(link)
					break;
			}
		},

	}
}
</script>